package com;


import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.citicpub_cloud.restfull.token.TokenInterceptor;

/**
 * 入口函数 community_server
 *
 * @author gengzhixin
 */
@EnableAutoConfiguration//启用自动配置  建议只有一个类带有该注解
@ComponentScan("com") //组件扫描
@EnableConfigurationProperties
@EnableTransactionManagement
@ServletComponentScan
public class ApplicationMain {

    private static Logger log = LoggerFactory.getLogger(ApplicationMain.class);

    public static void main(String[] args) {
        SpringApplication.run(ApplicationMain.class, args);

        synchronized (ApplicationMain.class){
            try {
                ApplicationMain.class.wait();
            } catch (InterruptedException e) {
                log.error("error", e);
                System.exit(-1);
            }
        }


    }
    
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
    
    @Configuration
    static class WebMvcConfigurer extends WebMvcConfigurerAdapter {

       
        @Bean
        @Primary
        @ConfigurationProperties(prefix = "spring.datasource")
        public DataSource primaryDataSource() {
            return DataSourceBuilder.create().build();
        }
        
        @Bean
        @Primary
        public JdbcTemplate primaryJdbcTemplate(DataSource dataSource) {
            return new JdbcTemplate(dataSource);
        }
        
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(new TokenInterceptor()).addPathPatterns("/**");
            super.addInterceptors(registry);
        }   
        
    }

}
